<template>
    <div class="common banner">
        <innerCommon 
            :location="location"
        >
            <template slot="left">
                <span>banner列表</span>
            </template>
            <div slot="right">
                <a-button type="primary" @click="addBox()">新增</a-button>
            </div>
            <div slot="table">
        
            <a-table 
                :rowKey="record=>record.id"
                :columns="columns" 
                size="middle"
                :dataSource="bannerList" 
                :pagination="pagination"
                @change="changePage"
                bordered>
                <div slot="banner_img" class="banner_img" slot-scope="text,record">
                    <img :src="record.img" alt="">
                </div>
                <div slot="action" class="tableAction" slot-scope="text,record">
                    <span @click="editBanner(record)">修改</span>
                    <confirmBox
                        @handleOk="deleteBanner(record.id)"
                        :typeName="'删除'"
                        :noticeInfo="'banner'"
                        :noticeType="''"
                    ></confirmBox>
                    <!-- <span @click="deleteBanner(record)">删除</span> -->
                    <span @click="move('up',record)">上移</span>
                    <span @click="move('down',record)">下移</span>
                </div>
            </a-table>
        </div>
    </innerCommon>
    <a-modal
        :title="title"
        :visible="isAdd"
        @ok="handleOk"
        @cancel="cancelBox()"
        okText="确认"
        cancelText="取消"
        :destroyOnClose="true"
        width="800px"
        class="bannerUpload"
        >
        <div>
            <eform
                v-if="fields||title=='新增banner'"
                :formData="formData"
                class="form"
                ref="form"
                :fields="fields"
                :hasFeedback="false"
            >
                <div slot="model">
                    <a-select
                        @focus="changeModule"
                        @change="changeHandleModule"
                        v-decorator="[
                        'module',
                        { rules: [{ required: true, message: '请选择模块' }] },
                        ]"
                        placeholder="请选择模块"
                    >
                        <template v-for="(value,index) in model" >
                            <a-select-option 
                                :key="index"
                                :value="value.id"
                                v-if="bannerList.filter(item=>item.link==value.name).length==0||value.name=='首页'"
                                >
                                {{value.name}}
                            </a-select-option>
                        </template>
                    </a-select>
                </div>
                <div slot="banner_url" class="bannerUrl">
                    <a-upload
                        accept=".png,.jpg"
                        name="avatar"
                        listType="picture-card"
                        class="avatar-uploader"
                        :showUploadList="false"
                        :action="imgUrl+'common/upload'"
                        :beforeUpload="beforeUpload"
                        @change="handleChange"
                    >
                        <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
                        <div v-else>
                        <a-icon :type="loading ? 'loading' : 'plus'" />
                        <div class="ant-upload-text">上传</div>
                        </div>
                    </a-upload>
                    <div class="warning" v-if="current">
                        <p v-if="current==1">首页：最佳尺寸1920*352</p>
                        <p v-if="current!=1">其他页： 最佳尺寸1920*261</p>
                    </div>
                </div>
            </eform>
        </div>
    </a-modal>
    </div>
</template>
<script>

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const columns=[{
        title: '序号',
        dataIndex:'index',
        width:80
    },{
        title: '所属模块',
        dataIndex:'module'
    },{
        title: 'banner图片',
        scopedSlots: { customRender: 'banner_img'}
    },{
        title: '链接地址',
        dataIndex:'link'
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
}]
import confirmBox from "@/components/common/confirmBox"
import innerCommon from "@/components/common/innerCommon"
import eform from '@/components/common/form'
import {bannerListApi,addBannerApi,editBannerApi,deleteBannerApi,commonMoveApi} from "@/request/api.js"
export default {
    name:'banner',
    components:{eform,innerCommon,confirmBox},
    data(){
        const formData=[{
                label:"所属模块",
                scopedSlots:{customRender:'model'}
            },{
                label:"上传图片",
                scopedSlots:{customRender:'banner_url'}
            },{
                label:"图片路径",
                prop:"img",
                placeholder:'输入图片路径',
                rules:[{required:true,message:'输入图片路径'}],
                disabled:true
            },{
                label:"链接地址",
                prop:"link",
                placeholder:'输入链接地址',
            }
        ]
        return{
            columns,
            formData,
            pagination:{pageSize:10,total:0},
            bannerList:[],
            isAdd:false,
            searchInfo:{
                keyword:'',
                page:1,
                pageSize:10,
                module:''
            },
            fields:{},
            title:'新增banner',
            imgUrl:window.g.apiUrl,
            imageUrl:'',
            loading:false,
            model:[
                {'name':'首页','id':1},
                {'name':'教学课堂','id':2},
                {'name':'名师讲堂','id':3},
                {'name':'证书查询','id':4},
                {'name':'实训中心','id':5},
                {'name':'资讯中心','id':6},
                {'name':'1+X服务平台','id':7},
                {'name':'产教融合','id':8}
            ],
            allModel:[
                {'name':'首页','id':1},
                {'name':'教学课堂','id':2},
                {'name':'名师讲堂','id':3},
                {'name':'证书查询','id':4},
                {'name':'实训中心','id':5},
                {'name':'资讯中心','id':6},
                {'name':'1+X服务平台','id':7},
                {'name':'产教融合','id':8}
            ],
            location:[],
            current:null,
        }
    },
    mounted(){
        this.location=[{
            name:"信息发布管理",
            path:''
        },{
            name:"banner图管理",
            path:''
        }]
        this.init()
    },
    methods:{
        init(){
            this.getToken(bannerListApi,this.searchInfo,(res)=>{
                this.bannerList = res.data.rows.map((item,index)=>({
                    ...item,
                    'module':this.allModel.filter(value=>value.id==item.module)[0].name,
                    index:(this.searchInfo.page-1)*10+index+1,
                }))
                this.pagination.total = res.data.count;
            })
        },
        onSearch(data){
            this.searchInfo.keyword=data
            this.init()
        },
        changePage(data){
            this.searchInfo.page=data.current
            this.init()
        },
        changeModule(){
            this.model=this.model.filter(item=>this.bannerList.filter(value=>value.module==item.name).length==0||item.id==1)
        },
        changeHandleModule(data){
            this.current=data
        },
        addBox(){
            this.title="新增banner"
            this.isAdd=true
            this.fields={}
            this.imageUrl=''
        },
        editBanner(data){
            this.title="修改banner"
            this.isAdd=true
            this.fields=data
            this.imageUrl=data.img
        },
        handleOk(){
            let api=''
            let formData={}
            this.$refs.form.form.validateFields().then(res=>{
                if(this.title=='新增banner'){
                    api=addBannerApi
                    formData=res
                }else{
                    api=editBannerApi
                    if(typeof(res.module)=='string'){
                        formData={...res,'bannerId':this.fields.id,'module':this.model.filter(item=>item.name==res.module)[0].id}
                    }else{
                        formData={...res,'bannerId':this.fields.id}
                    }
                }
                this.getToken(api,formData,(res)=>{
                    this.$message.success(res.message)
                    this.isAdd = false
                    this.init()
                })
            })
        },
        deleteBanner(data){
            this.getToken(deleteBannerApi,{'bannerId':data},res=>{
                this.$message.success(res.message)
                this.init()
            })
        },
        cancelBox(){
            this.$refs.form.form.resetFields()
            this.isAdd=false
            this.fields={}
        },
        handleChange(info) {
            if (info.file.status === 'uploading') {
                this.loading = true;
                return;
            }
            if (info.file.status === 'done') {
                getBase64(info.file.originFileObj, imageUrl => {
                this.imageUrl = imageUrl;
                this.loading = false;
                this.$refs.form.form.setFieldsValue({['img']:info.file.response.data.imgUrl[0]})
                });
            }
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('只允许上传jpg,png格式的图片');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('图片大小要小于2M');
            }
            return isJpgOrPng && isLt2M;
        },
        move(arrow,record){
            let sort = record.sort
            let index = record.index
            let tar_pos
            if((index==1&&arrow=='up')||(index==this.bannerList.length&&arrow=='down')){
                tar_pos = null
            }else{
                tar_pos = arrow == 'up'?this.bannerList[index-2].sort:this.bannerList[index].sort
            }
            this.getToken(commonMoveApi,{'key':'banner','curPos':sort,'targetPos':tar_pos},()=>{
                this.init()
            })
        }
    }
}
</script>
<style lang="stylus" scoped>
.avatar-uploader
    img     
        width:200px;
.banner
    .banner_img
        img
            width:100px;
    .bannerUrl
        position:relative;
        .warning
            position:absolute;
            right:0;
</style>
<style lang="stylus">
.bannerUpload
    .bannerUrl
        display:flex;
        .warning
            p
                margin:0;
                line-height:32px;
                color:red
            
</style>
